const { ishas } = require('../serves/userlogin')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
module.exports = {
    async isnull(ctx, next) {
        const { username, password } = ctx.query
        if (username.length == 0 || password.length == 0) {
            return ctx.body = {
                code: 400,
                msg: '用户名或密码不能为空'
            }
        }
        await next()
    },
    async jiami(ctx, next) {
        const salt = bcrypt.genSaltSync(10);
        // 将密码和salt值一起散列化
        const password = bcrypt.hashSync(ctx.query.password, salt);
        ctx.query.password = password
        await next()
    },
    async ishas(ctx, next) {
        const { username } = ctx.query
        const result = await ishas({ username })
        if (result) {
            return ctx.body = {
                code: 0,
                msg: '用户名存在!'
            }
        }
        await next()
    },
    async isok(ctx, next) {
        const { username, password } = ctx.query
        const rudata = await ishas({ username })
        if (!rudata) {
            return ctx.body = {
                code: 0,
                msg: "账号不存在!"
            }
        }
        const isMatch = bcrypt.compareSync(password, rudata.password);
        if (!isMatch) {
            return ctx.body = {
                code: 0,
                msg: "账号或密码错误!"
            }
        }
        ctx.token = jwt.sign({ id: rudata.id, username: rudata.username }, "ximo", { expiresIn: "1days" })
        const { password: rupassword, ...outerdata } = rudata.dataValues
        ctx.id = rudata.id
        ctx.userdata = outerdata
        await next()
    }
}